package com.xw.config;

import cn.hutool.core.util.StrUtil;
import com.xw.common.Constants;
import com.xw.dao.UserTokenDao;
import com.xw.entity.UserToken;
import com.xw.exp.ServiceException;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
/**
 * @Description: token拦截器
 * @Author: ASUS
 * @Date: 2024/12/19 09:15
 * @Version: 1.0
 */
public class Md5TokenInterceptor implements HandlerInterceptor {

    @Resource
    private UserTokenDao userTokenDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        // 判断是否为获取CSRF Token的接口路径，如果是则直接放行，不进行token相关验证
        if ("/web/token".equals(requestURI)) {
            return true;
        }

        // 1 从请求头获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Constants.UNAUTHORIZED.getCode(), "token过期重新登录");
        }

        // 2 查询数据库进行比对
        UserToken userToken = userTokenDao.selectByToken(token);
        if (Objects.isNull(userToken)) {
            throw new ServiceException(Constants.UNAUTHORIZED.getCode(), "token过期重新登录");
        }

        return true;
    }
}